<script setup lang="ts">
defineOptions({
  name: "supplyReminder"
});

import { ref, reactive, onMounted, onUnmounted, markRaw, getCurrentInstance, inject } from "vue";
import type { FormInstance, FormRules } from "px-ui";
import { PxMessage } from "px-ui";
import { querySupplyReminderList, ignoreSupplyReminder, createSupplyReminderOrder, batchCreateSupplyReminderOrder } from "@/api/modules/operation";
import commonTable from "@/views/common/components/commonTable/index.vue";
import commonSearch from "@/views/common/components/commonSearch/index.vue";
import batchCreateMessageBox from "@/views/gas/components/batchCreateMessageBox.vue";
import ReSegmented, { type OptionsType } from "@/components/ReSegmented";
import { Edit, Hide } from "@px-ui/icons-vue";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";
import { computed } from "vue";

const gap = 88;
const defaultHeight = 606;
const objectModelTableRef = ref<HTMLElement | null>(null);
const commonTableRef = ref<CommonTable.TableRefType>(null);
const commonSearchRef = ref<CommonSearch.SearchFormRefType>(null);
const scrollbarHeight = ref<number>(defaultHeight);
const params = ref<any>({});
const dialogFormVisible = ref<boolean>(false);
const ignoreId = ref<string>("");
const ids = ref<Array<any>>([]);
const isShowBatchCreateMessageBox = ref<boolean>(false);
const batchCreateMessageBoxData = ref<Array<any>>([]);

interface RuleForm {
  remark: string;
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  remark: ""
});

const rules = reactive<FormRules<RuleForm>>({
  remark: [{ required: true, message: "请输入备注！", trigger: ["blur", "change"] }]
});

const options: Array<OptionsType> = [
  {
    label: "未处理"
  },
  {
    label: "已处理"
  }
];

const segmentedActiveTab = ref<number>(0);

const searchOption: Array<CommonSearch.SearchOption> = [
  {
    label: "内容",
    key: "reminderContent",
    value: "",
    type: "input",
    placeholder: "请输入内容"
  },
  {
    label: "时间",
    key: "startTime",
    realKeys: ["startTime", "endTime"],
    value: [],
    type: "daterange",
    span: 8
  }
];

const tableCloumns = computed(() => {
  const tc: Array<CommonTable.TableCloumnsType> = [
    {
      label: "创建时间",
      prop: "createTime"
    },
    {
      label: "内容",
      prop: "reminderContent"
    }
  ];
  if (segmentedActiveTab.value === 0) {
    return tc;
  } else {
    tc.push({
      label: "操作记录",
      prop: "processStatusDesc"
    });
    tc.push({
      label: "备注",
      prop: "remark"
    });
  }
  return tc;
});

const operationOptions = computed(() => {
  const oo: Array<CommonTable.operationOptionItemType> = [
    {
      content: "开单",
      auth: "GAS_OPERATION_ACIDDRUMMANAGE_FILLINFWAGON_CREATEBTN",
      isHidden({ row }: any) {
        // processStatus 	0:未处理 1:已开单 2:已忽略
        return row.processStatus !== 0;
      },
      icon: markRaw(Edit),
      click: (scope: any) => create(scope)
    },
    {
      content: "忽略",
      auth: "GAS_OPERATION_ACIDDRUMMANAGE_FILLINFWAGON_IGNOREBTN",
      isHidden({ row }: any) {
        // processStatus 	0:未处理 1:已开单 2:已忽略
        return row.processStatus !== 0;
      },
      icon: markRaw(Hide),
      click: (scope: any) => ignore(scope)
    }
  ];
  return segmentedActiveTab.value === 0 ? oo : null;
});

let defaultParams: any = {
  // taskType  业务类型(1:气瓶 2：酸桶 3:槽车)
  taskType: 3,
  // 是否已处理
  processed: false
};
let currentParams: any = {};

const getRowKey = row => {
  return row.id;
};

// const headerCellStyleFn = ({ row, column, rowIndex, columnIndex }: CommonTable.CellType): Record<string, string> => {
//   const style = {};
//   if (columnIndex === 1) {
//     style["text-align"] = "center";
//   }
//   return style;
// };

const selectionChangeHandler = (val: Array<any>) => {
  ids.value = [];
  if (val?.length) {
    ids.value = val.map(item => item.id);
  }
};

const changeHandler = ({ index = 0 }: any) => {
  defaultParams.processed = index === 1 ? true : false;
  updateParams();
};

const updateParams = () => {
  params.value = { ...defaultParams, ...currentParams };
};

const submitSearchFormHandler = (form: any) => {
  currentParams = { ...currentParams, ...form };
  updateParams();
};

const resetSearchFormHandler = () => {
  currentParams = {};
  updateParams();
};

const { proxy }: any = getCurrentInstance();

const batchExportFn = useThrottleFn(async () => {
  const url = "/operation/api/v1/gas/supplyReminder/exportData";
  const params = commonTableRef.value.getParams();
  proxy.download("post", url, params);
}, delay);

const batchCreateFn = useThrottleFn(async () => {
  if (!!ids.value.length) {
    const loading = proxy.useInitLoading();
    const reqDTOList = ids.value.map(id => ({ id }));
    const params = { reqDTOList };
    const res = await batchCreateSupplyReminderOrder(params, () => {
      loading.close();
    });
    const flag = res.createTaskBatchDTOList.some(item => !item.res);
    if (flag) {
      batchCreateMessageBoxData.value = res.createTaskBatchDTOList;
      isShowBatchCreateMessageBox.value = true;
    } else {
      PxMessage.success("批量开单成功！");
      commonTableRef.value.clearSelection();
      commonTableRef.value.queryTableData();
    }
    loading.close();
  } else {
    PxMessage.error("请选择工单！");
  }
}, delay);

const closeHandler = () => {
  commonTableRef.value.clearSelection();
  commonTableRef.value.queryTableData();
};

const create = async scope => {
  const {
    row: { id = "" }
  } = scope;
  if (!id) return;
  await createSupplyReminderOrder(id);
  PxMessage.success("开单成功！");
  commonTableRef.value.queryTableData();
};

const ignore = scope => {
  const {
    row: { id = "" }
  } = scope;
  if (!id) return;
  ignoreId.value = id;
  ruleForm.remark = "";
  dialogFormVisible.value = true;
};

const ignoreCancelHandler = () => {
  if (!ruleFormRef.value) return;
  ruleFormRef.value.resetFields();
  dialogFormVisible.value = false;
};

const ignoreSubmitHandler = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      const id = ignoreId.value;
      const { remark } = ruleForm;
      const params = { id, remark };
      await ignoreSupplyReminder(params);
      PxMessage.success("已忽略！");
      ignoreCancelHandler();
      commonTableRef.value.queryTableData();
    } else {
      console.error("error submit!", fields);
    }
  });
};

onMounted(async () => {
  await useUpdateDomHeight(scrollbarHeight, objectModelTableRef, gap, defaultHeight);
});

onUnmounted(() => useCancelUpdateDomHeight());
</script>

<template>
  <div class="supply-reminder">
    <div class="supply-reminder-segmented">
      <ReSegmented v-model="segmentedActiveTab" :options="options" :boxShadow="false" @change="changeHandler" />
      <div class="supply-reminder-search">
        <commonSearch
          v-if="searchOption?.length"
          ref="commonSearchRef"
          :row-num="3"
          :operationSpan="3"
          :option="searchOption"
          @submit="submitSearchFormHandler"
          @reset="resetSearchFormHandler"
        />
      </div>
    </div>
    <div class="supply-reminder-btns">
      <px-button v-has="'GAS_OPERATION_ACIDDRUMMANAGE_FILLINFWAGON_EXPORTBTN'" type="primary" plain @click="batchExportFn">批量导出</px-button>
      <px-button
        v-show="segmentedActiveTab === 0"
        v-has="'GAS_OPERATION_ACIDDRUMMANAGE_FILLINFWAGON_BATCH_CREATEBTN'"
        type="primary"
        plain
        @click="batchCreateFn"
        >批量开单</px-button
      >
    </div>
    <div ref="objectModelTableRef" class="supply-reminder-table">
      <commonTable
        ref="commonTableRef"
        indexNeed
        :selection="segmentedActiveTab === 0"
        :operationOptions="operationOptions"
        :tableCloumns="tableCloumns"
        :height="scrollbarHeight"
        :row-key="getRowKey"
        :axiosApi="querySupplyReminderList"
        :params="params"
        @selection-change="selectionChangeHandler"
      />
    </div>

    <px-dialog v-model="dialogFormVisible" destroy-on-close title="忽略">
      <px-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
        <px-form-item label="备注" prop="remark">
          <px-input v-model.trim="ruleForm.remark" type="textarea" maxlength="200" show-word-limit placeholder="请输入备注！" />
        </px-form-item>
      </px-form>
      <template #footer>
        <span class="dialog-footer">
          <px-button @click="ignoreCancelHandler">取消</px-button>
          <px-button type="primary" @click="ignoreSubmitHandler"> 确定 </px-button>
        </span>
      </template>
    </px-dialog>

    <batchCreateMessageBox
      v-if="isShowBatchCreateMessageBox"
      v-model="isShowBatchCreateMessageBox"
      :data="batchCreateMessageBoxData"
      @close="closeHandler"
    />
  </div>
</template>

<style lang="scss" scoped>
.supply-reminder {
  width: 100%;
  background-color: #fff;

  .supply-reminder-segmented {
    display: flex;
    gap: 16px;
    align-items: center;

    .supply-reminder-search {
      flex: 1;
      // width: 100%;
      // margin-top: 16px;
    }
  }

  .supply-reminder-btns {
    display: flex;
    align-items: center;
    margin-top: 16px;
  }

  .supply-reminder-table {
    margin-top: 16px;
  }
}
</style>
